﻿using System;
using System.ComponentModel.Composition;
using MyMusicPlayer.Applications.ViewModels;
using System.Waf.Applications;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using MyMusicPlayer.Utils;
using MyMusicPlayer.Domain;
using System.Collections.ObjectModel;
using MyMusicPlayer.Applications.Services;
using MyMusicPlayer.Presentation.Views;
using System.IO;
using System.Collections.Generic;

namespace MyMusicPlayer.Applications.Controllers
{
    [Export]
    internal class ApplicationController
    {
        private readonly ShellService shellService;
        private readonly PlaylistController playlistController;
        private readonly ControlPanelController controlPanelController;

        private readonly ShellViewModel shellViewModel;
        private readonly PlaylistViewModel playlistViewModel;
        private readonly ControlPanelViewModel controlPanelViewModel;

        private readonly DelegateCommand openFileCommand;   // 弹窗，导入本地音乐文件
        private readonly DelegateCommand openFolderCommand; // 弹窗，导入文件夹下所有音乐文件

        private ShellWindow shellWindow;
        private ControlPanelView controlPanelView;


        [ImportingConstructor]
        public ApplicationController(ShellService shellService, PlaylistController playlistController, ShellViewModel shellViewModel,
            PlaylistViewModel playlistViewModel, ControlPanelController controlPanelController, ControlPanelViewModel controlPanelViewModel)
        {
            this.shellService = shellService;
            this.playlistController = playlistController;
            this.controlPanelController = controlPanelController;

            this.shellViewModel = shellViewModel;
            this.playlistViewModel = playlistViewModel;
            this.controlPanelViewModel = controlPanelViewModel;

            openFileCommand = new DelegateCommand(OpenFileCommand);
            openFolderCommand = new DelegateCommand(OpenFolderCommand);
        }


        public void Initialize()
        {
            shellService.ShellView = shellViewModel.View;
            shellViewModel.OpenFileCommand = openFileCommand;
            shellViewModel.OpenFolderCommand = openFolderCommand;
            shellWindow = shellViewModel.View as ShellWindow;
            shellWindow.Closing += ShellWindow_Closing;
            shellWindow.Closed += ShellWindow_Closed;
            controlPanelView = controlPanelViewModel.View as ControlPanelView;

            playlistController.Initialize();
            controlPanelController.Initialize();
        }


        /// <summary>
        /// 弹窗，导入本地音乐文件
        /// </summary>
        private void OpenFileCommand()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "音频文件(*.mp3;*.wav)|*.mp3;*.waf";
            openFileDialog.Title = "添加本地音乐文件";

            if (openFileDialog.ShowDialog() == true)
            {
                //Stream s = openFileDialog.OpenFile();
                string fullPath = openFileDialog.FileName; // D:\\CloudMusic\\星条旗のピエロ - まらしぃ.mp3
                MusicInfo musicInfo = AudioFileHelper.GetMusicInfoByFileFullPath(fullPath);

                // 判断是否重复添加歌曲
                if (CheckMusicInfoExist(musicInfo))
                {
                    MessageBox.Show("不能重复添加歌曲！");
                    return;
                }

                // 添加到播放列表中
                musicInfo.Index = playlistViewModel.MusicList.Count + 1;
                playlistViewModel.MusicList.Add(musicInfo);
                // 添加到本地数据库中
                XMLHelper.AddToPlaylistCache(musicInfo);
            }
        }


        /// <summary>
        /// 检查歌曲是否已经存在于播放列表中。
        /// </summary>
        /// <param name="musicInfo"></param>
        /// <returns>True表示已有重复项！</returns>
        public bool CheckMusicInfoExist(MusicInfo musicInfo)
        {
            foreach (var item in playlistViewModel.MusicList)
            {
                if (item.Id.Equals(musicInfo.Id))
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// 弹窗，导入文件夹下所有音乐文件
        /// </summary>
        private void OpenFolderCommand()
        {
            using (var fbd = new System.Windows.Forms.FolderBrowserDialog())
            {
                System.Windows.Forms.DialogResult result = fbd.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    List<MusicInfo> temp = AudioFileHelper.GetAllAudioFile(fbd.SelectedPath);

                    // 检查重复项，已存在播放列表中的音乐不能添加
                    List<MusicInfo> list = new List<MusicInfo>();
                    foreach (var item in temp)
                    {
                        if (!CheckMusicInfoExist(item))
                        {
                            list.Add(item);
                        }
                    }

                    // 加入播放列表
                    foreach (var musicInfo in list)
                    {
                        // 添加到播放列表中
                        musicInfo.Index = playlistViewModel.MusicList.Count + 1;
                        playlistViewModel.MusicList.Add(musicInfo);
                        // 添加到本地数据库中
                        XMLHelper.AddToPlaylistCache(musicInfo);
                    }

                    MessageBox.Show("添加了 " + list.Count + " 首音乐");
                    System.Console.WriteLine("添加了 " + list.Count + " 首音乐");
                }
            }
        }


        // 退出软件时，记录当前的音量到配置文件中
        // 系统会先调用Closing，再调用Closed
        private void ShellWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 弹窗提示是否确定要退出
            MessageBoxResult result = MessageBox.Show("您确定要退出吗？", null, MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
            System.Console.WriteLine(result);
            if (result == MessageBoxResult.Cancel)
            {
                e.Cancel = true; // 中断点击事件
            }
            // 记录音量
            XMLHelper.SetVolume(controlPanelView.volume.Value);
        }

        private void ShellWindow_Closed(object sender, EventArgs e)
        {
            //Application.Current.Shutdown(); // 正常结束
            Environment.Exit(0);              // 强制结束
        }


        #region 启动与关闭软件
        public void Run()
        {
            shellViewModel.Show();
        }

        public void Shutdown()
        {
        }
        #endregion
    }
}
